/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.common.tool.CommonUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.entity.CommodityRecord;
import org.springblade.modules.restaurant.entity.CommodityRecordRelation;
import org.springblade.modules.restaurant.enums.CommodityRecordStatusEnums;
import org.springblade.modules.restaurant.excel.CommodityRecordRelationExcel;
import org.springblade.modules.restaurant.service.ICommodityRecordRelationService;
import org.springblade.modules.restaurant.service.ICommodityRecordService;
import org.springblade.modules.restaurant.vo.CommodityRecordVO;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 货物采购记录 控制器
 *
 * @author Blade
 * @since 2025-01-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("/restaurant/commodityrecord")
@Tag(name = "货物采购记录", description = "货物采购记录接口")
public class CommodityRecordController extends BladeController {

	private ICommodityRecordService commodityRecordService;
	private ICommodityRecordRelationService commodityRecordRelationService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入commodityRecord")
	public R<CommodityRecord> detail(CommodityRecord commodityRecord) {
		CommodityRecord detail = commodityRecordService.getOne(Condition.getQueryWrapper(commodityRecord));
		return R.data(detail);
	}


	/**
	 * 详情
	 */
	@GetMapping("/getDetail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入commodityRecord")
	public R<CommodityRecordVO> getDetail(CommodityRecord commodityRecord) {
		CommodityRecordVO res = new CommodityRecordVO();

		CommodityRecord detail = commodityRecordService.getOne(Condition.getQueryWrapper(commodityRecord));
		BeanUtil.copyProperties(detail, res);

		List<CommodityRecordRelation> infos = commodityRecordRelationService.list(Wrappers.lambdaQuery(new CommodityRecordRelation())
			.eq(CommodityRecordRelation::getCommodityRecordId, detail.getId()));

		res.setInfo(infos);
		return R.data(res);
	}

	/**
	 * 分页 货物采购记录
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入commodityRecord")
	public R<IPage<CommodityRecord>> list(@ParameterObject CommodityRecordVO commodityRecord, @ParameterObject Query query) {
		LambdaQueryWrapper<CommodityRecord> wrapper = Wrappers.lambdaQuery(commodityRecord);
		if (Func.isNotEmpty(commodityRecord.getSearchTime())) {
			wrapper.between(CommodityRecord::getCreateTime, commodityRecord.getSearchTime()[0], commodityRecord.getSearchTime()[1]);
		} else {
			Date now = DateUtil.now();
			// 获取今天开始时间
			String startTime = DateUtil.format(now, CommonUtil.START_DATE_FORMAT);
			// 获取当前时间
			String endTime = DateUtil.format(now, DateUtil.PATTERN_DATETIME);

			wrapper.between(CommodityRecord::getCreateTime, startTime, endTime);
		}
		wrapper.eq(ObjectUtil.isNotEmpty(commodityRecord.getUserId()), CommodityRecord::getUserId, commodityRecord.getUserId());
		wrapper.orderByDesc(CommodityRecord::getCreateTime);
		IPage<CommodityRecord> pages = commodityRecordService.page(Condition.getPage(query), wrapper);
		return R.data(pages);
	}

	/**
	 * 自定义分页 货物采购记录
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入commodityRecord")
	public R<IPage<CommodityRecordVO>> page(@ParameterObject CommodityRecordVO commodityRecord, @ParameterObject Query query) {
		IPage<CommodityRecordVO> pages = commodityRecordService.selectCommodityRecordPage(Condition.getPage(query), commodityRecord);
		return R.data(pages);
	}

	/**
	 * 新增 货物采购记录
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description = "传入commodityRecord")
	public R save(@Valid @RequestBody CommodityRecord commodityRecord) {
		return R.status(commodityRecordService.save(commodityRecord));
	}

	/**
	 * 修改 货物采购记录
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入commodityRecord")
	public R update(@Valid @RequestBody CommodityRecord commodityRecord) {
		return R.status(commodityRecordService.updateById(commodityRecord));
	}

	/**
	 * 新增或修改 货物采购记录
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入commodityRecord")
	public R submit(@Valid @RequestBody CommodityRecord commodityRecord) {
		return R.status(commodityRecordService.saveOrUpdate(commodityRecord));
	}


	/**
	 * 删除 货物采购记录
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		commodityRecordService.deleteLogic(Func.toLongList(ids));
		return R.status(commodityRecordRelationService.remove(Wrappers.lambdaQuery(CommodityRecordRelation.class)
			.in(CommodityRecordRelation::getCommodityRecordId, Func.toLongList(ids))));
	}

	@PostMapping("/confirm")
	@Operation(summary = "采购单确认", description = "传入ids")
	public R confirm(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(commodityRecordService.confirm(Func.toLongList(ids)));
	}

	@GetMapping("/exportCheck")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "导出前检查", description = "传入searchDate")
	public R exportCheck(@RequestParam String[] searchTime) {

		Date now = DateUtil.now();
		// 获取今天开始时间
		String startTime = DateUtil.format(now, CommonUtil.START_DATE_FORMAT);
		// 获取当前时间
		String endTime = DateUtil.format(now, DateUtil.PATTERN_DATETIME);

		if (searchTime != null && searchTime.length == 2) {
			startTime = searchTime[0];
			endTime = searchTime[1];
		}
		return R.data(commodityRecordService.exportCheck(startTime, endTime));
	}

	/**
	 * 导出采购记录
	 */
	@SneakyThrows
	@GetMapping("/export")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出采购记录", description = "传入searchTime")
	public void export(CommodityRecordVO commodityRecord, HttpServletResponse response) {
		String[] searchTime = commodityRecord.getSearchTime();
		Date now = DateUtil.now();
		// 获取今天开始时间
		String startTime = DateUtil.format(now, CommonUtil.START_DATE_FORMAT);
		// 获取当前时间
		String endTime = DateUtil.format(now, DateUtil.PATTERN_DATETIME);

		if (searchTime != null && searchTime.length == 2) {
			startTime = searchTime[0];
			endTime = searchTime[1];
		}

		// 采购明细
		List<CommodityRecordRelation> commodityRecordRelationList = commodityRecordRelationService.list(Wrappers.<CommodityRecordRelation>lambdaQuery()
			.between(CommodityRecordRelation::getCreateTime, startTime, endTime)
			.eq(BaseEntity::getStatus, CommodityRecordStatusEnums.AUDITED.getStatus())
			.eq(ObjectUtil.isNotNull(commodityRecord.getUserId()), BaseEntity::getCreateUser, commodityRecord.getUserId())
		);
		// 过滤备注不为空
		List<CommodityRecordRelation> list1 = commodityRecordRelationList.stream().filter(item -> StrUtil.isNotBlank(item.getRemark())).toList();
		List<CommodityRecordRelationExcel> listExcel1 = commodityRecordService.exportCommodity(list1,false);

		// 获取备注为空
		List<CommodityRecordRelation> list2 = commodityRecordRelationList.stream().filter(item -> StrUtil.isBlank(item.getRemark())).toList();
		List<CommodityRecordRelationExcel> listExcel2 = commodityRecordService.exportCommodity(list2,true);

		List<CommodityRecordRelationExcel> list = new ArrayList<>();
		list.addAll(listExcel1);
		list.addAll(listExcel2);

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("采购明细", StandardCharsets.UTF_8);

		String time = DateUtil.format(now, CommonUtil.DATE_TIME_FORMAT);
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + "_" + time + ".xlsx");
		EasyExcel.write(response.getOutputStream(), CommodityRecordRelationExcel.class).sheet("采购明细").doWrite(list);
	}

}
